import React, { useEffect, useMemo, useState } from "react";
import { useDispatch } from "react-redux";
import { useNavigate } from "react-router-dom";
import { clearList, fetchContent, fetchTitle } from "../../app/home/homeSlice";
import { useAppDispatch, useAppSelector } from "../../app/hooks";
import { List } from "react-vant";
import ListItem from "../../components/listItem";
import "./style.css";

const Detail = () => {
  const navigate = useNavigate();

  const loading = useAppSelector((state) => state.home.loading);
  const title = useAppSelector((state) => state.home.title);
  const list = useAppSelector((state) => state.home.list);
  const error = useAppSelector((state) => state.home.error);
  const [activeIndex, setActiveIndex] = useState(0);
  const [pageCode, setPageCode] = useState(1);
  const dispatch = useAppDispatch();

  const id = useMemo(() => {
    return title[activeIndex]?.id;
  }, [title, activeIndex]);

  useEffect(() => {
    dispatch(fetchTitle());
  }, []);

  useEffect(() => {
    dispatch(fetchContent({ id }));
  }, [id]);

  return (
    <div className="home">
      {id}
      <input
        className="search"
        type="text"
        placeholder="请搜索"
        onClick={() => navigate("/search")}
      />
      <div className="title">
        <div>
          {title.map((v, i) => {
            return (
              <span
                className={i === activeIndex ? "active" : ""}
                onClick={() => {
                  setActiveIndex(i);
                  setPageCode(1);
                  dispatch(clearList());
                }}
                key={v.id}
              >
                {v.name}
              </span>
            );
          })}
        </div>
      </div>
      <List
        finished={error}
        errorText="没有更多数据了"
        finishedText="没有更多数据了"
        onLoad={async () => {
          dispatch(fetchContent({ id, pageCode: pageCode + 1 }));
          setPageCode(pageCode + 1);
        }}
      >
        <div className="list">
          {list.map((v, i) => {
            return (
              <ListItem
                v={v}
                onClick={() => navigate("/detail/" + v.id)}
              ></ListItem>
            );
          })}
        </div>
      </List>
    </div>
  );
};

export default Detail;
